#!/bin/bash

# Global variables
NUM_TESTS=0
NUM_PASS=0
NUM_FAIL=0
TESTS_DIR="tests/"
LOG_DIR="tests/results/"
print_error () {
  echo $1 1>&2
}

compare_results() {
  retval=0
  filesToDiff=$LOG_DIR$2'_results '$TESTS_DIR'/'$1'/'$2'.txt'
  if diff $filesToDiff > /dev/null 
  then 
    rm $LOG_DIR$2'_results' $LOG_DIR$1'_'$2'_log.txt'
  else
    retval=1
    diff $filesToDiff > $LOG_DIR$1'_'$2'_diff.txt'
  fi
  
  return $retval
}

run_test() {
  local testName=$1
  echo -n "Running $testName... "
  
  killall -q client server
  sleep 1
  
  NUM_TESTS=$((NUM_TESTS+1))
  local failcount=0
  
  local numClients=$2
	./server $numClients $LOG_DIR'server_results' &> $LOG_DIR$testName'_server_log.txt' &
	sleep 1

  for ((i=1; i <= numClients; i++))
  do
    burst=$((i*2+1))
    mem=$((i*2+2))
	  ./client ${!burst} ${!mem} $LOG_DIR'client'$i'_results' &> $LOG_DIR$testName'_client'$i'_log.txt' &
	  sleep 0.25
	done
  
  wait

	compare_results $testName "server"
  failcount=$((failcount+$?))

  for ((i=1; i <= numClients; i++))
  do
	  compare_results $testName "client$i"
	  failcount=$((failcount+$?))
	done

  killall -q client server
  if [ $? == 0 ]
  then
    print_error "Not all processes were killed!"
   	failcount=$((failcount+1))
  fi
    	
	
	if [ $failcount != 0 ]
	then 
	  echo "FAILED!"
	  print_error "$testName FAILED!"
    NUM_FAIL=$((NUM_FAIL+1))
	else
   NUM_PASS=$((NUM_PASS+1))
	  echo "PASSED!"
	fi
		
	return $failcount
}

# Main thread

# Do some pre-test clean up
killall -q client server
rm -rf $LOG_DIR/*

# Run test cases
run_test "test1" 1 7 15
run_test "test2" 2 4 15 10 15
run_test "test3" 3 14 7 2 7 9 2
run_test "test4" 4 1 6 9 9 8 3 21 2
run_test "test5" 5 1 2 3 4 5 6 7 8 9 10

echo "$NUM_PASS of $NUM_TESTS passed."
if [ $NUM_FAIL != 0 ]
then print_error "$NUM_FAIL tests FAILED!"
fi

exit $NUM_FAIL
